package com.dongxing.concyrrency.chapter10;

import java.util.Optional;
import java.util.stream.Stream;

/**
 * @author XavierDong
 **/
public class LockTest {

    public static void main(String[] args) throws InterruptedException {


        final BooleanLock booleanLock = new BooleanLock();
        Stream.of("T1", "T2", "T3", "T4").forEach(name -> {
            new Thread(name) {
                @Override
                public void run() {
                    try {
                        booleanLock.lock();
                        Optional.of(Thread.currentThread().getName() + " have the lock Monitor.").ifPresent(System.out::println);
                        work();
                        System.out.println(booleanLock.getBlockedThread());
                        System.out.println(booleanLock.getBlockedSize());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        booleanLock.unLock();
                    }
                }
            }.start();
        });

        Thread.sleep(100);
        booleanLock.unLock();

    }


    private static void work() {
        try {
            Optional.of(Thread.currentThread().getName() + " is working...").ifPresent(System.out::println);
            Thread.sleep(10_000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
